package com.kyzh.core.adapters.v3

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.core.beans.Game
import com.gushenge.core.beans.Sort
import com.gushenge.core.impls.GameImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.R
import com.kyzh.core.adapters.RankAdapter
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import org.jetbrains.anko.toast

class GameRankBottomAdapter(layout:Int,titles:ArrayList<Sort>, val t: Int):BaseQuickAdapter<Sort,BaseViewHolder>(layout,titles) {

    override fun convert(holder: BaseViewHolder, item: Sort) {
        val root = holder.getView<SmartRefreshLayout>(R.id.root)
        val recyclerView = holder.getView<RecyclerView>(R.id.recyclerView)
        val bean = mutableListOf<Game>()
        recyclerView.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        val adapter = RankAdapter(R.layout.rank_item, bean)
        recyclerView.adapter = adapter
        var p1 = 1
        var max1 = 1
        root.setEnableAutoLoadMore(false)
        root.setEnableRefresh(true)
        root.autoRefresh()
        root.setOnLoadMoreListener {
            if (p1 > max1) {
                context.toast(context.getString(R.string.noHaveMore))
                root.finishLoadMore()
            } else {
                GameImpl.rank(t, item.id, p1, object : ResultListener {
                    override fun success(beans: Any, p: Int, max: Int) {
                        beans as ArrayList<Game>
                        val gameArray = arrayListOf<Game>()
                        gameArray.addAll(beans)

                        bean.addAll(gameArray)
                        adapter.notifyDataSetChanged()
                        p1 = p
                        max1 = max
                        root.finishLoadMore()
                    }

                    override fun error(error: String) {
                        context.toast(context.getString(R.string.noHaveMore))
                        root.finishLoadMore()
                    }
                })
            }
        }
        root.setOnRefreshListener {
            GameImpl.rank(t, item.id, 1, object : ResultListener {
                override fun success(beans: Any, p: Int, max: Int) {
                    bean.clear()
                    bean.addAll(beans as ArrayList<Game>)
                    adapter.notifyDataSetChanged()
                    p1 = p
                    max1 = max
                    root.finishRefresh()
                }

                override fun error(error: String) {
                    adapter.setEmptyView(R.layout.empty)
                    root.finishRefresh()
                }
            })

        }
    }

}